var wechatMsgConstruct = require('./wechatMsgConstruct');
var config =require('../config/config');
module.exports = function (req, res, next) {
    console.log('设置密码');
    if (req.wechatMsg.MsgType == "text") {
        switch (true) {
            case /设置密码-[a-zA-Z0-9]{6,12}/.test(req.wechatMsg.Content):
            case /修改密码-[a-zA-Z0-9]{6,12}/.test(req.wechatMsg.Content):
            case /重置密码-[a-zA-Z0-9]{6,12}/.test(req.wechatMsg.Content):

                if(req.wechatUserStatus){
                    console.log('接受命令');
                    ResetPassword(req, res, next);
                }else {
                    var chat = {
                        Type: "text",
                        Content: require('../config/config').unRegistered
                    };
                    // 最后一步需要信息,并关闭数据库连接
                    req.mysqlConnection.end();
                    res.send(wechatMsgConstruct(req.wechatMsg, chat));
                }
                
                break;
            default:
                next();
                break;
        }
    } else {
        next()
    }

    function ResetPassword(req, res, next) {
        var newpass = req.wechatMsg.Content.split('-')[1];
        var query = req.mysqlConnection.query("UPDATE `" + config.mysql.database + "`.`ss_user` SET `pass` = '" + newpass + "' WHERE `ss_user`.`open_id` like '" + req.wechatMsg.FromUserName + "'");//炒作数据库
        query
            .on('error', function (err) {
                console.log('数据库连接失败', err)
            })
            .on('result', function (row) {

            })
            .on('end', function () {
                var chat = {
                    Type: "text",
                    Content: "设置成功,您的新密码是"+newpass
                };
                // 最后一步需要信息,并关闭数据库连接
                req.mysqlConnection.end();
                res.send(wechatMsgConstruct(req.wechatMsg, chat));
            });
    }

};